var commonUtil = require("../../../utils/commonUtil.js")
var globalData = getApp().globalData;
var httpsUrl = globalData.httpsUrl;
var imgUrl = globalData.imgUrl;
Page({
  data: {
    imgUrl: imgUrl,
    openid: '',
    hiddenFlag4: true,
    hiddenFlag5: true,
    couponzs: "选择劵",//劵抵扣展示
    cardzs: "选择卡",//卡抵扣展示
    total: "0.00",//需要支付的金额
    totalMoney: "0.00",//总计
    orderNo: '',//订单id
    cards: [],//卡列表
    coupons: [],//劵列表
    couponCode: "",
    memberCardCode: "",
  },

  loadData: function () {
    // var that = this;
    // this.voucher();//加载可用卡，劵
  },
  totalMoney: function (e) {
    let val = e.detail.value;
    this.setData({ totalMoney: val })
    this.voucher();//加载可用卡，劵
    if (!commonUtil.isEmpty(this.data.couponCode) || !commonUtil.isEmpty(this.data.memberCardCode)) {
      this.setData({ couponzs: "选择劵", cardzs: "选择卡", couponCode: "", memberCardCode: "",})
    }
    this.total();
  },
  //计算总金额
  total: function () {
    let total = 0.00;
    let that = this;
    let params = new Object();
    params.money = this.data.totalMoney;
    if (!commonUtil.isEmpty(this.data.couponCode)) {
      params.couponCode = this.data.couponCode;
    }
    if (!commonUtil.isEmpty(this.data.memberCardCode)) {
      params.memberCardCode = this.data.memberCardCode;
    }
    params.businessCode = wx.getStorageSync("businessCode");
    that.setData({ params: params });
    console.log("合计param:" + JSON.stringify(params));
    let openId = wx.getStorageSync("openidKey");
    commonUtil.showLoading("稍等...");
    wx.request({
      header: { "openId": openId, },
      url: httpsUrl + "/order/getOfflinePayMoney",
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        res = res.data;
        console.log("合计：" + JSON.stringify(res));
        if (res.result == 0) {
          that.setData({ total: res.data.cashPayMoney.toFixed(2) })
        }
      }
    })
  },
  //提交订单
  submitOrder: function () {
    var that = this;
    let total = this.data.total;
    let params = this.data.params;
    console.log("订单提交参数" + JSON.stringify(params));
    commonUtil.showLoading("提交中...");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/json" },
      url: httpsUrl + "/order/OfflinePay",
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        console.log("提交订单返回:" + JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          that.setData({ orderNo: res.data })
          that.goPay();
          //that.paySuccess();
        } else {
          commonUtil.showModal(res.msg);
        }
      }
    })
  },
  //获取openid
  goPay: function () {
    let total = this.data.total;//合计为0，跳过在线支付
    if (total > 0) {
      var that = this;
      wx.login({
        success: function (res) {
          wx.showLoading({ title: '请稍等...', })
          wx.request({
            header: { "content-Type": "application/x-www-form-urlencoded" },
            url: httpsUrl + "/wechat/getOpenId",
            dataType: "json",
            method: "POST",
            data: { "code": res.code, "agentCode": globalData.agentCode },
            success: function (res) {
              wx.hideLoading();
              res = res.data;
              console.log("获取openid返回:" + JSON.stringify(res));
              if (res.result == 0) {
                let data = JSON.parse(res.data);
                console.log(data.openid);
                that.setData({ openid: data.openid })
                that.pay();
              } else {
                console.log("获取openid失败：" + res.msg);
              }
            }
          })
        }
      })
    } else if (total == 0) {
      this.paySuccess();
    }
  },
  //支付
  pay: function () {
    let that = this;
    let params = new Object();
    params.orderNo = this.data.orderNo;
    params.openid = this.data.openid;
    console.log(JSON.stringify(params));
    commonUtil.showLoading("去支付...");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/order/payParam",//统一下单返回支付参数
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        console.log("统一下单返回" + JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          var data = res.data;
          //调起支付
          wx.requestPayment(
            {
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': 'MD5',
              'paySign': data.paySign,
              'success': function (res) {
                console.log("支付调起成功");
                that.paySuccess();
              },
              'fail': function (res) {
                console.log("用户取消支付");
                wx.switchTab({
                  url: '../orderList/orderList',
                })
              },
              'complete': function (res) { }
            })
        } else {
          commonUtil.showModal("支付失败：" + res.msg);
        }
      }
    })
  },

  paySuccess: function () {
    wx.navigateTo({
      url: '../paySuccess/paySuccess',
    })
  },
  //优惠劵板块
  juanModal: function () {
    if (this.data.hiddenFlag4 == true) {
      //this.voucher();
    }
    this.setData({ hiddenFlag4: !this.data.hiddenFlag4, });
  },
  //我的劵。卡列表
  voucher: function () {
    let that = this;
    let params = new Object();
    params.money = this.data.totalMoney;
    params.businessCode = wx.getStorageSync("businessCode");
    console.log("卡劵param:" + JSON.stringify(params));
    let openId = wx.getStorageSync("openidKey");
    commonUtil.showLoading("稍等...");
    wx.request({
      header: { "openId": openId, },
      url: httpsUrl + "/order/offlinePayCardAndCoupon",
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        console.log("劵卡：" + JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          that.setData({ coupons: res.data.coupon, cards: res.data.card })
          // console.log("res.data.coupon.length:"+res.data.coupon.length);
          if (res.data.coupon.length == 0) {
            that.setData({ couponzs: "无可使用劵" })
          }
          if (res.data.card.length == 0) {
            that.setData({ cardzs: "无可使用卡" })
          }
        }
      }
    })
  },
  //选择劵
  selectVoucher: function (e) {
    let id = e.currentTarget.id;
    let list = this.data.coupons;
    let row = list[id];
    this.setData({ couponzs: row.discountRule, couponCode: row.code })
    this.total();
    this.setData({ hiddenFlag4: !this.data.hiddenFlag4, });
  },
  card: function () {
    if (this.data.hiddenFlag4 == true) {
      //this.voucher();
    }
    this.setData({ hiddenFlag5: !this.data.hiddenFlag5, });
  },
  selectCard: function (e) {
    let id = e.currentTarget.id;
    let list = this.data.cards;
    let row = list[id];
    this.setData({ cardzs: row.discountRule, memberCardCode: row.code })
    this.total();
    this.setData({ hiddenFlag5: !this.data.hiddenFlag5, });
  },

  onLoad: function (options) {
    this.loadData();
  },

  onShow: function () {
  },
})